
package org.mushroomdb.transaction;

import java.util.HashMap;

import org.mushroomdb.interceptor.CompositeInterceptor;
import org.mushroomdb.interceptor.InterceptorService;
import org.mushroomdb.service.Service;

/**
 * @author Tomas
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class TransactionService implements Service {
    
    //guarda pares Thread/Transaction
    private HashMap transactions = new HashMap();
    
   
    public void initialize() {
        this.transactions = new HashMap();
    }
    
    public void beginTransaction(){
       Thread thread = Thread.currentThread();
       Transaction trx = new Transaction();
       this.transactions.put(thread,trx);
    }
    
    public void commitTransaction(){
        InterceptorService interceptorService = InterceptorService.getInstance();
        CompositeInterceptor compositeInterceptor = (CompositeInterceptor) interceptorService.getInterceptor();
        Transaction trx = getCurrentTrx();
        compositeInterceptor.beforeCommit();
        trx.commit();
        compositeInterceptor.afterCommit();
        this.transactions.remove(Thread.currentThread());
    }
    
    public void rollBackTransaction(){
        Transaction trx = getCurrentTrx();
        trx.rollback();
        this.transactions.remove(Thread.currentThread());
    }
    
    public Transaction getCurrentTrx() {
       Thread thread = Thread.currentThread();
       Transaction trx = (Transaction) this.transactions.get(thread);
       return trx;
    }
    
    public void removeTransaction(Thread thread){
        this.transactions.remove(thread);
    }

}
